package com.lanou.realm;

import com.lanou.bean.User;
import com.lanou.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 18/3/10.
 */
public class MyPerRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;

    @Override
    public String getName() {
        return "myPerRealm";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //************假数据开始************
        List<String> permissionList = new ArrayList<>();
        permissionList.add("user:create");
        permissionList.add("user:query");
        List<String> roleList = new ArrayList<>();
        roleList.add("CEO");
        roleList.add("DE");
        //************假数据结束************
        //授权信息对象,用来保存所有的角色和权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleList);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String phone = (String) authenticationToken.getPrincipal();
        User user = userMapper.userLogin(phone);

        if (user==null) {
            throw new UnknownAccountException("未知账号/没有该账号");
        }
        String password = new String((char[]) authenticationToken.getCredentials());
        if (!user.getU_password().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }
        return new SimpleAuthenticationInfo(user,password,getName());
    }
}
